// https://www.lintcode.com/problem/binary-tree-tilt/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    protected int ret;
    
    Solution() {
        ret = 0;
    }
    
    /**
     * @param root: the root
     * @return: the tilt of the whole tree
     */
    public int findTilt(TreeNode root) {
        // Write your code here
        if (root != null) {
            int ls = sum(root.left);
            int rs = sum(root.right);
            ret += Math.abs(ls - rs);
            findTilt(root.left);
            findTilt(root.right);
        }
        return ret;
    }
    
    protected int sum(TreeNode node) {
        if (node == null) {
            return 0;
        }
        return node.val + sum(node.left) + sum(node.right);
    }
}